
using System;
using QdbUnit;
using QdbUnit.Extensions;
using QdbUnit.Extensions.Fixtures;
using Qdb;
using Qdb.Config;
using Qdb.Ext;
using Qdb.Internal;
using Qdb.Internal.Threading;

namespace QdbUnit.Extensions.Fixtures
{
	public abstract class AbstractSoloQdbFixture : AbstractQdbFixture
	{
		private IExtObjectContainer _db;

		protected AbstractSoloQdbFixture()
		{
		}

		public sealed override void Open(IQdbTestCase testInstance)
		{
			Assert.IsNull(_db);
			IConfiguration config = CloneConfiguration();
			ApplyFixtureConfiguration(testInstance, config);
			_db = CreateDatabase(config).Ext();
			ListenToUncaughtExceptions(ThreadPool());
			PostOpen(testInstance);
		}

		private IThreadPool4 ThreadPool()
		{
			return ThreadPoolFor(_db);
		}

		/// <exception cref="System.Exception"></exception>
		public override void Close()
		{
			PreClose();
			if (null != _db)
			{
				Assert.IsTrue(_db.Close());
				try
				{
					ThreadPool().Join(3000);
				}
				finally
				{
					_db = null;
				}
			}
		}

		public override bool Accept(Type clazz)
		{
			return !typeof(IOptOutSolo).IsAssignableFrom(clazz);
		}

		public override IExtObjectContainer Db()
		{
			return _db;
		}

		public override LocalObjectContainer FileSession()
		{
			return (LocalObjectContainer)_db;
		}

		public override void ConfigureAtRuntime(IRuntimeConfigureAction action)
		{
			action.Apply(Config());
		}

		protected virtual void PreClose()
		{
		}

		protected virtual void PostOpen(IQdbTestCase testInstance)
		{
		}

		protected abstract IObjectContainer CreateDatabase(IConfiguration config);
	}
}
